var flag=true;
var $resMsg=$("#res-msg");
$(".back").on("touchend", function (e) {
	e.preventDefault();
    e.stopPropagation();
    window.history.back();
});
//查看挂牌房源
$('.check-sale').on("touchend", function (e) {
	e.preventDefault();
    e.stopPropagation();
    var dealSearchVal= common.getLocalData("historySearchRecord");
    window.location.href="hangVillageSearchResult.html?dealSearchVal="+dealSearchVal[0];
});
$(function () {
    var $houseSaleListPanel=$("#house-saleList");
    var $searchVillageFail=$('.search-village-fail');
    var globalHost=common.globalHost;
    var listPort=common.dealQueryVillageSaleHouse;
    var documentHeight=0;
    var windowHeight=0;
    //获取villageId;
    var villageId=common.getQueryString('villageId');
    var villageTitle=$('#village-title');
    	villageTitle.html(villageId);
    
    var sendData={};
	    sendData={
	        pageIndex:1,
	        pageSize:10,
	        villageId:villageId
	    };
    var url=globalHost+listPort;
    var formData=common.getSendDataByForm('form');
		sendData = $.extend({}, sendData, formData);
		historyControl.layerShow();
    	requestData();
    function requestData() {
    	// historyControl.layerShow();
        $.ajax({
            data:sendData,
            type: "POST",
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            dataType:"json",
            url:url,
            success:function(data){
            	historyControl.layerHide();
                $resMsg.text("").hide();
                if(typeof data==="string"){
                    data=JSON.parse(data);
                }
                if(data.totalNumber==0){
                	$houseSaleListPanel.hide();
                	$searchVillageFail.show();
                }else{
                	$houseSaleListPanel.show();
                	$searchVillageFail.hide();
                	data=data.data;
                	if(!data.length){
	                    $resMsg.text("已经没有更多信息了").show();
	                }else{
	                    var responseDom=buildListDomOfMobileByDataList({
	                        loadingSelector:$resMsg,
	                        imgBasePath:globalHost,
	                        pageTargetType:"_self",
	                        dataList:data
	                    });
	                    // if(data.length<10){
	                    // 	$resMsg.text("已经没有更多信息了").show();
	                    // }
	                    $houseSaleListPanel.append(responseDom);
	                    documentHeight=$(document).height();
	                    sendData.pageIndex++;
	                }
                }
            },
            timeout:10000,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
	            historyControl.layerHide();
                // console.log("网络不畅，请稍后重试");
                historyControl.errDialog("网络不畅，请稍后重试");
                
            }
        });
    };
	//筛选条件的显示与隐藏
	var $parentNav=$('.parent-list');
    var $myForm=$('#myform');
	$parentNav.children('li').off('tap').on('tap',function(e){
		var $this=$(this);
		var formHide=$myForm.find('.form-hide');
		var index = $this.index();
		if($this.hasClass('marker')){
			formHide.hide();
			$this.removeClass('marker');
			formHide.eq(index)[0].style.display==="none"?historyControl.maskHide():historyControl.maskShow();
		}else if($this.hasClass('clear-marker')){
			$this.addClass("marker").siblings().removeClass('marker');
			if(formHide.eq(index)[0].style.display==="none"){
				formHide.hide()&&formHide.eq(index).slideDown(200);
				historyControl.maskShow();
			}else{
				formHide.hide();
				historyControl.maskHide();
			}	
		}else{
			formHide.eq(index)[0].style.display==="none"?historyControl.maskShow():historyControl.maskHide();
			formHide.hide()&&formHide.eq(index).slideDown(200);
			$this.addClass('marker').siblings().removeClass('marker');
			historyControl.maskShow();
		}
		e.preventDefault();
		return false;
	});
	//总价
	var $totalPrice=$('#total-price');
	var $totalMaxInput=$('#totalMax');
	var $totalMinInput=$('#totalMin');
	checkChild({
		targetSelector:$totalPrice,
		parentSelector:$parentNav,
		MaxInput:$totalMaxInput,
		MinInput:$totalMinInput
	})
	//筛选条件给隐藏域赋值面积
	function checkChild(options){
		var $targetSelector=$(options.targetSelector);
		var $MaxInput=$(options.MaxInput);
		var $MinInput=$(options.MinInput);
		var $parentSelector=$(options.parentSelector);
		$targetSelector.find('li').off('tap').on('tap',function(e){
			var $this=$(this);
			//阻止事件冒泡，防止手指滑动的时候屏幕下面的层滑动；
			$this.parent().off("touchmove").on("touchmove",function(ev){
				cancelBubble=true;
				ev.stopPropagation();
				ev.preventDefault();
				return false;
			});
			$this.hasClass('check')?null:$this.addClass('check').siblings().removeClass('check');
			// $parentSelector.find('li').hasClass('marker')?$parentSelector.find('.marker').removeClass('marker').html($this.html()):null;
			var parentId=$targetSelector.attr("id");
			var clearMarker=$parentSelector.find('li').hasClass('clear-marker');
			var marker=$parentSelector.find('li').hasClass('marker');
			if(!!marker&&parentId==="total-price"){
				$(".totalHouse").removeClass('marker').addClass('clear-marker').html($this.html());
			}else if(!!clearMarker&&parentId==="total-price"){
				$(".totalHouse").html($this.html());
			};
			historyControl.maskHide();
			//给隐藏域赋值
			$MaxInput.val('');
			$MinInput.val('');
			var dataValue = $this.attr('data-value');
			if(dataValue.indexOf('-')>-1){
				$MaxInput.val(dataValue.split('-')[1]);
				$MinInput.val(dataValue.split('-')[0]);
			}
			$this.parent().hide();
			sendData={
		        pageIndex:1,
		        pageSize:10,
		        villageId:villageId
		    };
			var formData=common.getSendDataByForm('form');
			sendData = $.extend({}, sendData, formData);
			$houseSaleListPanel.html('');
			historyControl.layerShow();
			$searchVillageFail.hide();
        	$resMsg.text('').hide();
			requestData();
			e.preventDefault();
			return false;
		})
	}
	//价格排序;
	var $priceSort=$('#price-sort');
	var $sortTypeInput=$('#sortType')
	dealTimeFilter({
		targetSelector:$priceSort,
		parentSelector:$parentNav,
		dealTimeInput:$sortTypeInput
	});
	function dealTimeFilter(options){
		var $targetSelector=$(options.targetSelector);
		var $dealTimeInput=$(options.dealTimeInput);
		var $parentSelector=$(options.parentSelector);
		$targetSelector.find('li').off('tap').on('tap',function(e){
			var $this=$(this);
			$this.hasClass('check')?null:$this.addClass('check').siblings().removeClass('check');
			//阻止事件冒泡，防止手指滑动的时候屏幕下面的层滑动；
			$this.parent().off("touchmove").on("touchmove",function(ev){
				cancelBubble=true;
				ev.stopPropagation();
				ev.preventDefault();
				return false;
			});
			var parentId=$targetSelector.attr("id");
			var clearMarker=$parentSelector.find('li').hasClass('clear-marker');
			var marker=$parentSelector.find('li').hasClass('marker');
			if(!!marker&&parentId==="price-sort"){
				$(".more").removeClass('marker').addClass('clear-marker').html($this.html());
			}else if(!!clearMarker&&parentId==="price-sort"){
				$(".more").html($this.html());
			};
			historyControl.maskHide();
			$dealTimeInput.val('5');
			var dataValue = $this.attr('data-value');
			$dealTimeInput.val(dataValue);
			$this.parent().hide();
			sendData={
		        pageIndex:1,
		        pageSize:10,
		        villageId:villageId
		    };
			var formData=common.getSendDataByForm('form');
			sendData = $.extend({}, sendData, formData);
			$houseSaleListPanel.html('');
			historyControl.layerShow();
			$searchVillageFail.hide();
        	$resMsg.text('').hide();
			requestData();
			e.preventDefault();
			return false;
		})
	};
	//签约时间
	var $signTimerSure=$('.sure-check');
	var $sliderInput=$('#slider-input');
	var $startDate=$('#startDate');
	var $endDate=$('#endDate');
	$signTimerSure.off('tap').on('tap',function(e){
		var $this=$(this);
		var parentId=$("#sign-time").attr("id");
		var clearMarker=$(".signTimer").hasClass('clear-marker');
		var marker=$(".signTimer").hasClass('marker');
		if(!!marker&&parentId==="sign-time"){
			$(".signTimer").removeClass('marker').addClass('clear-marker');
		}
		//添加隐藏域
		var arrHidden = $sliderInput.val().split(",");
		var startDate,endDate;
		if(arrHidden[0]<=12){
			startDate='2016-'+arrHidden[0];
		}else{
			startDate='2017-'+(arrHidden[0]-12);
		}
		if(arrHidden[1]<=12){
			endDate='2016-'+arrHidden[1];
		}else{
			endDate='2017-'+(arrHidden[1]-12);
		}
		$startDate.val(startDate);
		$endDate.val(endDate);
		historyControl.maskHide();
		$this.parent().parent().hide();
		sendData={
	        pageIndex:1,
	        pageSize:10,
	        villageId:villageId
	    };
		var formData=common.getSendDataByForm('form');
		sendData = $.extend({}, sendData, formData);
		$houseSaleListPanel.html('');
		historyControl.layerShow();
		$searchVillageFail.hide();
    	$resMsg.text('').hide();
		requestData();
		e.preventDefault();
		return false;
	});
	//点击返回
	var $clearCheck= $('.clear-check');
	$clearCheck.off('tap').on('tap',function(e){
		var $this=$(this);
		var parentId=$("#sign-time").attr("id");
		var clearMarker=$(".signTimer").hasClass('clear-marker');
		var marker=$(".signTimer").hasClass('marker');
		if(!!marker&&parentId==="sign-time"){
			$(".signTimer").removeClass('marker').addClass('clear-marker');
		}
		$this.parent().parent().hide();
		historyControl.maskHide();
		e.preventDefault();
		return false;
	});
	$(window).on("scroll",function (e) {
        windowHeight=$(window).height();
        if($(this).scrollTop()+windowHeight==documentHeight){
        	if(flag){
        		$resMsg.html('<span class="loading"></span>正在加载中呦~~').show();
        		requestData();
        	}else{
        		$resMsg.html('已经没有更多信息了').show();
        	}
            
        }
    });
    // 点击屏幕其他部位筛选条件div消失
	$('#mask').off('tap').on('tap',function(e){
		var $this=$(this);
		$this.hide();
		$myForm.find('.form-hide').hide();
		var optionLis=$parentNav.find("li");
		$.each(optionLis,function(idx,ele){
			if($(ele).hasClass("clear-marker")){
				$(ele).removeClass("marker");
			}else{
				$(ele).removeClass("marker");
			}

		})
		e.cancelBubble=true;
		e.stopPropagation();
		e.preventDefault();
		return false;
	});
	//阻止事件滑动；
	$(".sign-timer").off("touchmove").on("touchmove",function(ev){
		ev.stopPropagation();
		ev.preventDefault();
		return false;
	});
	$(".more-footer").off("touchmove").on("touchmove",function(ev){
		ev.stopPropagation();
		ev.preventDefault();
		return false;
	});
});
function buildListDomOfMobileByDataList(options) {
    var dataList=options.dataList||[];
    var imgBasePath=options.imgBasePath||"./";
    var pageTargetType=options.pageTargetType||"_blank";
    var $loading=$(options.loadingSelector);
    var arrTemp=[];
    var dataCount=0;
    $.each(dataList,function (idx, obj) {
        dataCount++;
        // var houseAddressText=obj['rowKey']===""?"":obj['rowKey'];//房屋地址
        var houseAreaText=obj['size']==null||obj['size']===""?"":"面积："+'<span>'+obj['size']+'</span>m²';//建筑面积
        var signTime=""
        if(obj['publishDate']==null||obj['publishDate']===""){
        	signTime="";
        }else{
        	var timePublishDate=new Date(obj['publishDate']);
        	var fullYear = timePublishDate.getFullYear();
        	var month = timePublishDate.getMonth()+1;
        	var day = timePublishDate.getDate();
        	signTime="签约时间："+fullYear+"年"+month+"月"+day+"日";
        }
        var addressDom=obj['rowKey']==null||obj['rowKey']===""?"":'<span class="address">'+obj['rowKey'].split("无").join("")+'</span>';
        var housereSource=obj['houseSource']==null||obj['houseSource']===""?"":"成交中介："+obj['houseSource'];
        var listingPriceDom=obj['totalCost']==null||obj['totalCost']===""? "" : '<span class="totalPrice">'+Math.round(Number(obj['totalCost']))+'万</span>';
        var unitPriceDom=obj['price']==null||obj['price']===""?"" : '<span class="unit-price">'+obj['price']+'元/m²</span>';
        var tempDom='<li class="panel">'+
                        '<p class="houseAddressText">'+addressDom+'</p>'+
                        '<div class="house-content">'+
	                        '<p class="houseAreaText">'+houseAreaText+listingPriceDom+'</p>'+
	                        '<p class="signTime">'+signTime+unitPriceDom+'</p>'+
	                        '<p class="housereSource">'+housereSource+'</p>'+
                        '</div>'
                    '</a>'+'</li>';
        arrTemp.push(tempDom) ;
    });
    // $loading.length>0?(dataList.length && dataList.length<10 || dataCount<10?(flag=false && $loading.text("已经没有更多信息了").show()):(flag=true && $loading.text("哈哈哈哈").hide())):"无点击加载选择器";
    if($loading.length>0){
    	if(dataList.length && dataList.length<10 || dataCount<10){
    		flag=false; 
    		$loading.text("已经没有更多信息了").show();
    	}else{
    		flag=true;
    		$loading.text("").hide();
    	}
    }
    return arrTemp.join("");
}